//index.js
//获取应用实例
const app = getApp()
var template = require('../../templateTabbar/templateTabbar.js');
//zouzou 选择时间
var date = new Date();
var currentHours = date.getHours();
var currentMinute = date.getMinutes();
//
var api = require('../../api.js');
var util = require('../../utils/util.js');

Page({
  data: {
    tel:"",
    loadingShow:false,
    distance:null,
    amount:null,
    discount: null,
    discount_notice: "订单优惠",
    price:null,
    total: null,
    swiperCurrent: 0,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    isorder:0,
    circular: true,
    isnew: 0,
    isshare: 0,
    indicatorCo: "#eee",
    indicatoraAC: "#666",
    imgUrls: [
      '',
    ],
    zf:{
      images:"",
      name:"转发好友赢福利",
      html: "首单优惠30元，转发再享20元",
    },    
    flynumber: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    //接送等标题切换
    winHeight: "",//窗口高度
    currentTab: 0, //预设当前项的值
    scrollLeft: 0, //tab标题的滚动条位置
    //接送二级
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0
    },
    destination:null,    
    radio: [
      // { name: 'jingji', value: '经济型 X4座', imgurl: '../../images/car-jinji.png' },
      { name: 'shushi', value: '四人座', checked: 'true', imgurl: '../../images/car-shushi.png' },
      { name: 'shangwu', value: '六人座', imgurl: '../../images/car-shangwu.png' }
    ],
    chooseImg: "../../images/car-right.png",
    choosehidn: true,
    ChooseBtn1:false,
    ChooseBtn2: true,
    heighth: "480rpx",
    //出发时间
    select_datavaule:null,
    startDate: "请选择日期",
    multiArray: [['今天', '明天', '3-2', '3-3', '3-4', '3-5'], [0, 1, 2, 3, 4, 5, 6], [0, 10, 20]],
    multiIndex: [0, 0, 0],
    duration:null, //路线预计送达时间
    producttype:1,  //默认业务类型 1 接机 2 送机 3接站 4送站
    selectPerson: true,
    firstPerson: '杭州萧山国际机场',
    Fromtrain: '请选择火车站',
    Totrain: '请选择火车站',
    selectArea: false,
    ToPerson: '杭州萧山国际机场',
    starAddress: ''
  },
  clearCache:function(){
    wx.removeStorageSync("orderInfo");
    wx.removeStorageSync("fight");
    //五千 清空选择目的地 记录
    wx.removeStorageSync("selectedAddress");
    wx.removeStorageSync("selectedFromPlant");
    this.setData({ 
      firstPerson: '杭州萧山国际机场',
      ToPerson:'杭州萧山国际机场',
      startDate:"请选择日期",
      Fromtrain: '请选择火车站',
      Totrain: '请选择火车站',
      destination:null,
      starAddress:null,
      ChooseBtn1:false,//显示去选车按钮
      ChooseBtn2: true,//隐藏预约按钮
      select_datavaule:null,//发出时间
      multiIndex:[0,0,0],
      choosehidn: true,//点击选项卡隐藏预约车模块
      selectPerson: true,//下拉默认
      selectArea: false,
    })
  },
  setbanner:function(){
    var that = this;
    util.NetRequest({
      url: api.getbanner,
      data: {type:1},
      success: function (res) {
        res.forEach(function (item, index, input) {
          input[index] = item.images;
        })
        that.setData({ imgUrls: res });
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  setzfbanner: function () {
    var that = this;
    util.NetRequest({
      url: api.getbanner,
      data: { type: 2 },
      success: function (res) {
        //res.forEach(function (item, index, input) {
        //  input[index] = item.images;
        //})
        that.setData({ zf: res[0]});
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  onLoad: function () {    
    //var openid = wx.getStorageSync('openid');
    //console.log("index:" +app.globalData.openid); 
    this.clearCache();
    this.JiejiFrom();
    this.setbanner();
    this.setzfbanner();
    template.tabbar("tabBar", 0, this)//0表示第一个tabbar
    //接送机切换tab
    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        console.log(calc)
        that.setData({
          winHeight: calc,
          loadingShow:true
        });
      }
    });
    //结束

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  //zouzou分享弹框
  ShareView: function (e) {
    var that = this;
    that.setData({
      showShare: (!that.data.showShare)
    })
  },

  //zouzou关闭乘车人弹框
  ContactClose: function (e) {
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  //zouzou修改乘车人弹框
  ContactPopup: function (e) {
    
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
    if (!that.data.showView)
    {
      var mobile = e.detail.value.tel;
      if (mobile.length == 0) {
        wx.showToast({
          title: '请输入手机号！',
          icon: 'none',
          duration: 1500
        })
        that.setData({
          showView: (!that.data.showView)
        })
        return false;
      }
      if (mobile.length != 11) {
        wx.showToast({
          title: '手机号长度有误！',
          icon: 'none',
          duration: 1500
        })
        that.setData({
          showView: (!that.data.showView)
        })
        return false;
      }
      var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
      if (!myreg.test(mobile)) {
        wx.showToast({
          title: '手机号有误！',
          icon: 'none',
          duration: 1500
        })
        that.setData({
          showView: (!that.data.showView)
        })
        return false;
      }
      that.setData({
        tel: e.detail.value.tel
      })
    }
  },
  //zouzou转发分享按钮
  onShareAppMessage: function () {
    var that = this;
    　　// 设置菜单中的转发按钮触发转发事件时的转发内容
    　　var shareObj = {
              title: "杭州汽车服务城",        // 默认是小程序的名称(可以写slogan等)
              path: '/pages/index/index',        // 默认是当前页面，必须是以‘/’开头的完整路径
      　　　　success: function (res) {
        　　　　　　// 转发成功之后的回调
        　　　　　　if (res.errMsg == 'shareAppMessage:ok') {
                      wx.request({
                        url: api.updateshare,
                        method: 'POST',
                        data: {
                          openid: wx.getStorageSync('openid')
                        },
                        header: {
                          'content-type': 'application/json'
                        },
                        success: function (res) {
                          wx.showToast({
                            title: '分享成功！',
                            icon: 'success',
                            duration: 1500
                          })
                        }
                      });
        　　　　　　}
      　　　　}
  　　};
　　return shareObj;
  },
  //zouzou接机出发地下拉
  //点击选择类型
  clickPerson: function () {
    var selectPerson = this.data.selectPerson;
    if (selectPerson == true) {
      this.setData({
        selectArea: true,
        selectPerson: false,
      })
    } else {
      this.setData({
        selectArea: false,
        selectPerson: true,
      })
    }
  },
  //zouzou 接机固定
  JiejiFrom: function (Planttype = "f"){
    var selectedFromPlant = { lat: 30.23438, lng: 120.43716, departure:"杭州萧山国际机场", fight_id:1};
    console.log(selectedFromPlant);
    if (Planttype == "f") {
      wx.setStorageSync("selectedFromPlant", JSON.stringify(selectedFromPlant));
    } else if (Planttype == "t") {
      selectedFromPlant.address = selectedFromPlant.departure;
      wx.setStorageSync("selectedAddress", JSON.stringify(selectedFromPlant));
    }
  },
  //点击切换
  mySelect: function (e) {
    var postion = (e.target.dataset.position).split(",");
    var departure = e.target.dataset.me;
    var fight_id = 1;
    var selectedFromPlant = { lat: postion[0], lng: postion[1], departure: departure, fight_id: fight_id };
    if (e.target.dataset.type == "f"){
      wx.setStorageSync("selectedFromPlant", JSON.stringify(selectedFromPlant));
    } else if (e.target.dataset.type == "t"){
      selectedFromPlant.address = selectedFromPlant.departure;
      wx.setStorageSync("selectedAddress", JSON.stringify(selectedFromPlant));
    }
    
    this.setData({
      firstPerson: e.target.dataset.me,
      ToPerson: e.target.dataset.me,
      Fromtrain: e.target.dataset.me,
      Totrain: e.target.dataset.me,
      selectPerson: true,
      selectArea: false,
    })
    this.onShow();
  },
  ToSelect: function (e) {
    this.setData({
      ToPerson: e.target.dataset.to,
      selectPerson: true,
      selectArea: false,
    })
  },
  //zouzou出发时间
  //获取时间日期
  pickerTap: function () {
    var initPickData = util.common.getPickerData(this.data.multiIndex);
    this.setData(initPickData);
  },
  bindMultiPickerColumnChange: function (e) {
    this.data.multiIndex[e.detail.column] = e.detail.value;
    var initPickData = util.common.getPickerData(this.data.multiIndex);
    this.setData(initPickData);
  },

  bindStartMultiPickerChange: function (e) {

    var column01 = this.data.multiArray[0][e.detail.value[0]];
    var column02 = this.data.multiArray[1][e.detail.value[1]];
    var column03 = this.data.multiArray[2][e.detail.value[2]];
    var re_data = util.common.getPickerSelecterDate(column01, column02, column03);

    this.data.select_datavaule = re_data.year + "-" + re_data.month + "-" + re_data.day + " " + re_data.hours + ":" + re_data.minute + ":00";
    var startDate = re_data.formDay;
    this.setData({
      startDate: startDate
    })
    this.onShow();
  },
  //出发时间end
  showChangeList: function (){
    //wuqian
    wx.navigateTo({
      url: '/pages/searchaddress/list',
    })
  },
  //轮播图的切换事件
  // swiperChange: function (e) {
  //   this.setData({
  //     swiperCurrent: e.detail.current
  //   })
  // },
  //点击指示点切换
  chuangEvent: function (e) {
    this.setData({
      swiperCurrent: e.currentTarget.id
    })
  },
  //点击图片触发事件
  swipclick: function (e) {
    console.log(this.data.swiperCurrent);
    wx.switchTab({
      url: this.data.links[this.data.swiperCurrent]
    })
  },
  //事件处理函数  
  //预约订车- 处理下单参数
  bindViewTapCar: function () {
    var fight = wx.getStorageSync('selectedFromPlant');
    var fightJson = JSON.parse(fight);
    var selectedAdd = wx.getStorageSync("selectedAddress");
    var selectedAddJSON = JSON.parse(selectedAdd);
    var openid = wx.getStorageSync('openid');
    
    wx.setStorage({
      key: 'orderInfo',
      data: {
        departure: fightJson.departure,
        destination: selectedAddJSON.address,
        usetime: this.data.select_datavaule,
        openid: openid,
        cartype: 2,
        price: this.data.price,
        discount: this.data.discount,
        discount_notice: this.data.discount_notice,
        total: this.data.total,
        flight_id: fightJson.fight_id,
        producttype: this.data.producttype,
        distance: this.data.distance,
        rider:this.data.tel
      },
    })
    // console.log(wx.getStorageSync('orderInfo'));
    // return false;
    wx.navigateTo({
      url: '../carorder/carorder'
    })
  },
  paycheckbtn: function () {
    wx.navigateTo({
      url: '../paycheck/paycheck'
    })
  },
  //接送机切换
  // 滚动切换标签样式
  switchTab: function (e) {
    this.setData({
      currentTab: e.detail.current
    });
    this.checkCor();
  },
  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    var cur = e.target.dataset.current;
    if (this.data.currentTaB == cur) { return false; }
    else {
      this.setData({
        currentTab: cur,        
      })
    }
    this.clearCache();
     //切换到接送机获取机场地址及经纬度
    if (cur == 0) {
      if (this.data.tabArr.curHdIndex == 0) {
        this.JiejiFrom("f");
        this.setData({ producttype: 1 });
      }
      if (this.data.tabArr.curHdIndex == 1) {
        this.JiejiFrom("t");
        this.setData({ producttype: 2 });
      }
    }
    if (cur == 1) {
      if (this.data.tabArr.curHdIndex == 0) {
        this.setData({ producttype: 3 });
      }
      if (this.data.tabArr.curHdIndex == 1) {
        this.setData({ producttype: 4 });
      }
    }
    console.log("producttype:"+this.data.producttype);
  },
  //判断当前滚动超过一屏时，设置tab标题滚动条。
  checkCor: function () {
    if (this.data.currentTab > 4) {
      this.setData({
        scrollLeft: 300
      })
    } else {
      this.setData({
        scrollLeft: 0
      })
    }
  },
  //接送二级
  tabFun: function (e) {    
    this.clearCache();
    //获取触发事件组件的dataset属性
    var _datasetId = e.target.dataset.id;
    var producttype = e.target.dataset.producttype;
    //切换到接送机获取机场地址及经纬度
    if (producttype== 1) {
      this.JiejiFrom("f");
    }
    if (producttype == 2) {
      this.JiejiFrom("t");
    }    
    console.log("----" + _datasetId + "----");
    var _obj = {};
    _obj.curHdIndex = _datasetId;
    _obj.curBdIndex = _datasetId;
    this.setData({
      tabArr: _obj,
      producttype: producttype,
      choosehidn: true,//点击选项卡隐藏预约车模块
      producttype: producttype
    });
  },
  //航班号查询
  flightNumber: function (e) {
    wx.navigateTo({
      url: '../Searchflight/Searchflight'
    })
  },
  //选择车型
  getradio: function (e) {
    let index = e.currentTarget.dataset.id;
    let radio = this.data.radio;
    for (let i = 0; i < radio.length; i++) {
      this.data.radio[i].checked = false;
    }
    if (radio[index].checked) {
      this.data.radio[index].checked = false;
    } else {
      this.data.radio[index].checked = true;
    }
    let userRadio = radio.filter((item, index) => {
      return item.checked == true;
    })
    this.setData({ radio: this.data.radio })
    console.log(userRadio)
  },
  chooseCar: function () {
    this.setData({
      chooseImg: "../../images/car-right2.png"
    })
  },
  //获取当前出发点；地址
  getCurrentPoint: function () {
    wx.navigateTo({
      url: '/pages/searchaddress/list?f=c',
    })
  },
  gotoChoose: function (){    
    var fight = wx.getStorageSync('selectedFromPlant');   
    var selectedAdd = wx.getStorageSync("selectedAddress");
    console.log(selectedAdd);
    if (fight=="")
    {
      wx.showToast({
        title: '出发地不为空！',
        duration: 2000
      })
      return false;
    } 
    if (this.data.select_datavaule==null) {
      wx.showToast({
        title: '时间不为空！',
        duration: 2000
      })
      return false;
    }
    if (selectedAdd == "") {
      wx.showToast({
        title: '目的地不为空！',
        duration: 2000
      })
      return false;
    }
    if (this.data.isorder==0) {
      return false;
    }
    
    this.setData({
      choosehidn:false,
      ChooseBtn1:true,
      ChooseBtn2: false
    })
  },
  //选车结束
  
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  getinfo:function(){
    var that = this;
    wx.request({
      url: api.getuserinfo,
      method: 'POST',
      data: {
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.isnew != undefined) {
          that.setData({ isnew: res.data.isnew });
        }
        if (res.data.isshare != undefined) {
          that.setData({ isshare: res.data.isshare });
        }
        if (that.data.tel == "" && res.data.bindPhone != undefined) 
        {
          that.setData({ tel: res.data.bindPhone });
        }
        console.log("isnew:" + that.data.isnew);
        console.log("tel:" + that.data.tel);
      }
    });
  },
  //显示时
  onShow:function(){
    console.log(this.data.select_datavaule);
    this.getinfo();
    //{ lat: lat, lng: lng, address: address }
    var selectedFromPlant = wx.getStorageSync("selectedFromPlant");//选择接送航站楼--出发点
    var selectedAdd = wx.getStorageSync("selectedAddress");
    if (selectedFromPlant){
      var selectedFromPlantJSON = JSON.parse(selectedFromPlant);
      this.setData({
        starAddress: selectedFromPlantJSON.departure
      });
    }
    if (selectedAdd) {
      var selectedAddJSON = JSON.parse(selectedAdd);
      this.setData({ 
        destination: selectedAddJSON.address
      });
    }
    if (selectedAdd && selectedFromPlant && this.data.select_datavaule){
      var selectedFromPlantJSON = JSON.parse(selectedFromPlant);
      var selectedAddJSON = JSON.parse(selectedAdd);
      var startDate = this.data.select_datavaule;
      console.log(startDate);

      this.getDistance({
        startDateTime: startDate,
        from_lat: selectedFromPlantJSON.lat,
        from_lng: selectedFromPlantJSON.lng,
        to_lat: selectedAddJSON.lat,
        to_lng: selectedAddJSON.lng,
        producttype: this.data.producttype
      });
    }
    
  },
  // 计算 距离和价格
  getDistance:function (data){
    console.log(data);
    var that = this;
    util.NetRequest({
      url: api.getDistance,
      data:data,
      success:function(res){
        if(res.error_code){
          util.common.showTipError(res.error_message);
          that.setData({ isorder: 0 });
        }else{
          that.setData({ distance: res.distance });
          that.setData({ amount: res.amount });
          that.setData({ duration: res.time });
          wx.setStorageSync("polyline", JSON.stringify({ polyline: res.polyline, distance: res.distance, time: res.time }));
          that.setData({ isorder: 1 });
          if (that.data.isnew == 1) {
            that.setData({
              discount: res.first_discount,
              discount_notice: "首单优惠",
              total: that.data.amount,
              price: that.data.amount - res.first_discount
            })
          } else {
            
            that.setData({
              discount: res.discount,
              discount_notice: "订单优惠",
              total: that.data.amount,
              price: that.data.amount - res.discount
            })
            //var select_date = new Date(that.data.select_datavaule.replace(/-/, "/"));
            //var hour = parseInt(select_date.getHours());
            if (that.data.isshare == 1) {
              that.setData({
                discount: res.forward_discount,
                discount_notice: "转发优惠",
                total: that.data.amount,
                price: that.data.amount - res.forward_discount
              })
            }
          }
          
        }
        
      },
      fail: function (res){
        console.log(res)
      }
    })
  },
  ///添加行程路线
  showMapPath:function(){
    wx.navigateTo({
      url: '/pages/mapPath/path',
    })
  }
})
